package com.kumi.shop.product.exception;

import com.kumi.common.execption.Code;
import com.kumi.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.kumi.shop.product.controller")
public class ShopExceptionControllerAdvice {
    //
//
//        }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException e){
        Map<String,String> map = null;
        log.error("数据校验异常{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()){
            map = new HashMap<>();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String defaultMessage = fieldError.getDefaultMessage();
                String field = fieldError.getField();
                map.put(field,defaultMessage);
            }
        }
        return R.error(Code.VAILD_EXCEPTION.getCode(),Code.VAILD_EXCEPTION.getMsg()).put("data",map);
    }
}
